<?php
/*
=====================================================
 EE Vimeo Simple API plugin - by Jeremy Adams
-----------------------------------------------------
 http://www.jeremyadams.me/
-----------------------------------------------------
 Copyright (c) 2009 Jeremy Adams

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

=====================================================
 File: pi.vimeo_feed.php
-----------------------------------------------------
 Purpose: Display Vimeo Videos Using Curl and Vimeo Simple API
=====================================================
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);

$plugin_info = array(
						'pi_name'			=> 'Vimeo API Plugin',
						'pi_version'		=> '1.1.5',
						'pi_author'			=> 'Jeremy Adams',
						'pi_author_url'		=> 'jeremyadams.me',
						'pi_description'	=> 'Displays Vimeo Feeds',
						'pi_usage'			=> Vimeo_feed::usage()
					);

class Vimeo_feed {
	
	private static $feed_data;
	private static $feed_url;
	private static $type;
	private static $request;
	private static $hide_videos;
	private static $id;
	private static $show_before;
	private static $show_after;
	private static $width;
	private static $height;
	private static $class;
	private static $page;
	private static $limit;
	private static $show_pages;
	private static $use_url;
	private static $seg_start;
	private static $pagenation;
	private static $total;
	private static $ch;
	private static $page_arr;
	private static $video_requests = array('videos','likes','appears_in','all_videos','subscriptions','contacts_videos','contacts_like');
	private static $info_requests = array('info','albums','channels','groups','user_did','happened_to_user','contacts_did','happened_to_contacts','everyone_did','users');
	
	static function group()
	{
		global $TMPL, $FNS, $IN;
		
		self::$type='group';
		$out=self::_init();
		return $out;
	}
	
	static function channel()
	{
		global $TMPL, $FNS, $IN;
		
		self::$type='channel';
		$out=self::_init();
		return $out;
	}
	
	static function album()
	{
		global $TMPL, $FNS, $IN;
		
		self::$type='album';
		$out=self::_init();
		return $out;
	}
	
	static function video()
	{
		global $TMPL, $FNS, $IN;
		
		self::$type='video';
		$out=self::_init();
		return $out;
	}
	
	private function _get_request($request)
	{
		if ( in_array($request,self::$video_requests) )
		{
			$out=self::_list_videos(self::$page_arr['start'],self::$page_arr['end']);
			
		} elseif ( in_array($request,self::$info_requests) )
		{
			$out=self::_list_info();
		} else {
			$out='I have no idea what you are looking for!';
		}
		
		if (self::$show_pages)
		{
			$out.=self::$pagenation;
		}
		
		return $out;
	
	}
	
	private function _init()
	{
		global $TMPL, $FNS, $IN;
		self::$request = ($TMPL->fetch_param('request') == '') ? "videos" : $TMPL->fetch_param('request');
		self::$hide_videos = ($TMPL->fetch_param('hide_videos') == '') ? FALSE : $TMPL->fetch_param('hide_videos');
		self::$id = trim($TMPL->fetch_param('id'));
		self::$show_before = explode("|",trim($TMPL->fetch_param('show_before')));
		self::$show_after = explode("|",trim($TMPL->fetch_param('show_after')));
		self::$width = ($TMPL->fetch_param('width') == '') ? 400 : $TMPL->fetch_param('width');
		self::$height = ($TMPL->fetch_param('height') == '') ? 300 : $TMPL->fetch_param('height');
		self::$class = $TMPL->fetch_param('class');
		self::$page = ($IN->fetch_uri_segment('2')=='') ? 1 : $IN->fetch_uri_segment('2');
		self::$limit = ($TMPL->fetch_param('limit') == '') ? 5 : $TMPL->fetch_param('limit');
		self::$show_pages = ($TMPL->fetch_param('show_pages') == '') ? 0 : $TMPL->fetch_param('show_pages');
		self::$use_url = ($TMPL->fetch_param('use_url') == '') ? 0 : $TMPL->fetch_param('use_url');
		self::$pagenation='';
		self::$feed_url=self::_format_feed_url(self::$type,self::$id,self::$request);
		self::$feed_data=self::_get_feed(self::$feed_url);
		self::$total = count(self::$feed_data);
		self::$page_arr=self::_calc_pages(self::$total,self::$limit,self::$page);
		
		if ( ! self::$feed_data) // No Feed Data
		{
			return '<div class="'.self::$class.'">No Data Returned! - &#27809;&#26377;&#36820;&#22238;&#30340;&#25968;&#25454;! - &#25976;&#25818;&#27794;&#26377;&#36820;&#22238;! - Geen Teruggekeerde Gegevens! - Aucunes donn&#233;es renvoy&#233;es ! - Keine Daten zur&#252;ckgebracht! - &#922;&#945;&#957;&#941;&#957;&#945; &#963;&#964;&#959;&#953;&#967;&#949;&#943;&#959; &#949;&#960;&#953;&#963;&#964;&#961;&#949;&#966;&#972;&#956;&#949;&#957;&#959;! - Nessun dati restituiti! - &#12487;&#12540;&#12479;&#12399;&#25147;&#12425;&#12394;&#12363;&#12387;&#12383;! - &#50500;&#47924; &#51088;&#47308;&#46020; &#46028;&#47140;&#48372;&#45236;&#51648; &#50506;&#50520;&#45796;! - Nenhum dados retornou! - &#1053;&#1080;&#1082;&#1072;&#1082;&#1080;&#1077; &#1076;&#1072;&#1085;&#1085;&#1099;&#1077; &#1085;&#1077; &#1074;&#1086;&#1079;&#1074;&#1088;&#1072;&#1090;&#1080;&#1083;&#1080;! - &#161;Ningunos datos devueltos!</div>';
			break;
		}
		
		if ( (self::$page_arr['pages']>1) AND (self::$show_pages) )
		{
			self::$pagenation=self::_create_pagenation(self::$page_arr);
		}
		
		return self::_get_request(self::$request);
	}
	
	private function _list_videos($start,$end)
	{
		$i=0;
		$out='';
		foreach(self::$feed_data as $key=>$value)
		{
			if ( ( $i >= $start ) && ( $i < $end ) )
			{
				$out.='<div class="'.self::$class.'">';
				
				$out.=self::_show_response_data(self::$show_before,$value);
				
				if ( ! is_null($value['id']) AND ($value['id'] !== "") AND ( ! self::$hide_videos))
				{
				$out .= '<span class="player">
				<object width="'.self::$width.'" height="'.self::$height.'">
				<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='.$value['id'].'&amp;server=vimeo.com"></param>
				<param name="allowFullScreen" value="true"></param>
				<param name="wmode" value="transparent" />
				<param name="allowscriptaccess" value="always"></param>
				<embed src="http://vimeo.com/moogaloop.swf?clip_id='.$value['id'].'&amp;server=vimeo.com" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="'.self::$width.'" height="'.self::$height.'"></embed>
				</object>
				</span>';
				}
				
				$out.=self::_show_response_data(self::$show_after,$value);
				
				$out.='</div>
				
				';
			}
			
			$i++;
			if ($i==$end) break;
		}
		return $out;
	}
	
	private function _list_info()
	{
		$out='';
		$out.='<span class="'.self::$class.' info">';		
		$out.=self::_show_response_data(self::$show_before,self::$feed_data);			
		$out.=self::_show_response_data(self::$show_after,self::$feed_data);			
		$out.="</span>";
		return $out;
	}
	
	private function _show_response_data($show,$values)
	{
		$rd='';
		foreach($show as $name)
		{
			if ( ( ! is_null($name) ) AND ( $name !== "" ) AND ( array_key_exists($name, $values) ) )
			{ 
				if ( ! $values[$name] !== "" )
				{
					if ((stripos($name, "thumbnail")) || (stripos($name, "portrait")))
					{
						$rd .= '<span class="'.$name.'"><img src="'.$values[$name].'" alt="'.$values[$name].'" /><span>';
					} else
					{
						$rd .= '<span class="'.$name.'">'.$values[$name].'<span>';
					}
				}
			}
		}
		return $rd;
	}
	
	private function _calc_pages($total,$limit,$page)
	{
		$pa=array();
		if ($total > $limit)
		{
			$pa['start']=($page*$limit)-$limit;
			$pa['end']=$pa['start']+$limit;
			$pa['pages']=ceil($total/$limit);
		} else
		{
			$pa['start']=0;
			$pa['end']=$total;
			$pa['pages']=1;
		}
		return $pa;
	}
	
	private function _create_pagenation($pa)
	{
		global $FNS, $IN;

		$pn='<span class="pagenation">';
		for($j=1; $j<=$pa['pages']; $j++)
		{
			$pn.='<a href="'.$FNS->create_url($IN->fetch_uri_segment('1').'/'.$j).'" ';
			
			if ($j==self::$page)
			{
				$pn.='class="active" ';
			}
			$pn.='>'.$j.'</a>';
		}
		$pn.='</span>';
		return $pn;
	}
		
	private function _get_feed($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
		$fd = curl_exec($ch);	
		curl_close($ch);
		$fd = unserialize($fd);
		return $fd;
	}
	
	private function _format_feed_url($type,$id,$request)
	{		
		
		if ($type == "video")
		{
			$fu='http://vimeo.com/api/v2/video/'.$id.'.php';
		} elseif ($type == "user")
		{
			$fu='http://vimeo.com/api/v2/'.$id.'/'.$request.'.php';
		} else
		{
			$fu='http://vimeo.com/api/v2/'.$type.'/'.$id.'/'.$request.'.php';
		}
		return $fu;
	}
	

function usage()
{
ob_start(); 
?>
Display Vimeo Videos Using Curl and Vimeo API

		=============================
		The Tag
		=============================
		{exp:vimeo_feed:[type] id="[your id or name]" limit="max #/page" class="your wrapper class"}
        
		SHOW GROUP VIDEOS:
        {exp:vimeo_feed:group id="churchmediahub" limit="3" class="vimbox" show_before="user_portrait_small|user_name" show_pages="1"}
        
        SHOW CHANNEL VIDEOS:
        {exp:vimeo_feed:channel id="everythinganimated" limit="3" class="vimbox" show_before="title|description"}
        
        SHOW VIDEO:
        {exp:vimeo_feed:video id="7951816" limit="1" class="vimbox" show_before="title|url|upload_date||" show_after="description|user_name"}


		==============
		TAG PARAMETERS
		==============

        type= ---/! REMOVED VERSION 1.1.0 !/---
          -------------------

        request=
            [OPTIONAL]
            Type of return requested
            Available options depends on the request type: Please see REQUESTS below
            The default value is (videos)
          -------------------
          
        width= 
            [OPTIONAL]
            the height of the player. The default value is (425).
            ------------------- 

        height=
            [OPTIONAL]
            the width of the player. The default value is (344).
            ------------------- 
            
        class=
            [OPTIONAL]
            The <ul> container class
            ------------------- 
            
        limit=
            [OPTIONAL]
            Maximum number of videos to display
            ------------------- 
            
        show_before=
            [OPTIONAL]
            Response Data to show before the video
            **See options below
            ------------------- 
            
        show_after=
            [OPTIONAL]
            Response Data to show before the video
            **See RESPONSE DATA below
            ------------------- 
            
        show_pages=
            [OPTIONAL]
            Show Pagenation links. 0=off 1=on. Default is 0
            **See RESPONSE DATA below
            ------------------- 


        *Available REQUESTS
        =========================
        exp:vimeo_feed:user
        -------------------------

        info:
            User info for the specified user
        videos:
            Videos created by user
        likes:
            Videos the user likes
        appears_in:
            Videos that the user appears in
        all_videos:
            Videos that the user appears in and created
        subscriptions:
            Videos the user is subscribed to
        albums:
            Albums the user has created
        channels:
            Channels the user has created and subscribed to
        groups:
            Groups the user has created and joined
        contacts_videos:
            Videos that the user's contacts created
        contacts_like:
            Videos that the user's contacts like


		exp:vimeo_feed:group
        -------------------------
        videos
            Videos added to that group
        users
            Users who have joined the group
        info
            Group info for the specified group


		exp:vimeo_feed:channel
        -------------------------
        videos
            Videos in the channel
        info
            Channel info for the specified channel


		exp:vimeo_feed:album
        -------------------------
        videos
            Videos in the channel
        info
            Channel info for the specified channel

        
        **Available RESPONSE DATA
        -------------------------
        These options can be used in the show_before or show_after
        Separated by a pipe -> |
        example show_before="title|url|id|thumbnail_small"
        PLEASE VISIT: http://www.vimeo.com/api/docs/simple-api FOR ADDITIONAL RESPONSE DATA
        -------------------------
        
        title :    Video title
        
        url :    URL to the Video Page
        
        id :    Video ID
        
        description :    The description of the video
        
        thumbnail_small :    URL to a small version of the thumbnail
        
        thumbnail_medium :    URL to a medium version of the thumbnail
        
        thumbnail_large :    URL to a large version of the thumbnail
        
        user_name :    The user name of the video's uploader
        
        user_url :    The URL to the user profile
        
        upload_date :    The date/time the video was uploaded on
        
        user_portrait_small :    Small user portrait (30px)
        
        user_portrait_medium :    Medium user portrait (100px)
        
        user_portrait_large :    Large user portrait (300px)
        
        stats_number_of_likes :    # of likes
        
        stats_number_of_views :    # of views
        
        stats_number_of_comments :    # of comments
        
        duration :    Duration of the video in seconds
        
        width :    Standard definition width of the video
        
        height :    Standard definition height of the video
        
        tags :    Comma separated list of tags
        
        

        ======================
        EXAMPLE STYLE SHEET:
        ======================
        .vimbox{
        margin:10px;
        width:500px;
        }
        .vimbox .title{
        color:#03cef2;
        font-size:1.7em;
        line-height:26px;
        font-weight:700;
        }
        .vimbox .upload_date{
        font-size:.8em;
        color:#efefef;
        }
        .vimbox .description{
        border:1px solid #ccc;
        background:#efefef;
        color:#fff;
        width:80%;
        padding:10px;
        margin:0 0 20px 0;
        }

        // Thanks
----------------------------------------------


<?php
$buffer = ob_get_contents();
	
ob_end_clean(); 

return $buffer;
}
// END


}